import os
import base64
import json
import warnings

warnings.filterwarnings("ignore", category=DeprecationWarning)  # 忽略警告

def calculate_sum_check(data):
    """计算简单的加法校验和（8位）"""
    return sum(byte for byte in data) & 0xFF  # 取低8位

def split_bin_to_frames(bin_file_path, block_size=256):
    """
    将 .bin 文件分帧，生成 JSON 格式的 OTA 数据包
    :param bin_file_path: .bin 文件路径
    :param block_size: 每帧大小（字节）
    :return: 包含所有帧的 JSON 列表
    """
    frames = []

    with open(bin_file_path, "rb") as f:
        bin_data = f.read()
        total_size = len(bin_data)
        frame_count = (total_size + block_size - 1) // block_size  # 计算总帧数

        for seq in range(frame_count):
            offset = seq * block_size
            chunk = bin_data[offset: offset + block_size]
            b64_data = base64.b64encode(chunk).decode("ascii")
            checksum = calculate_sum_check(chunk)  # 使用加法校验

            frame = {
                "type": "data",
                "seq": seq + 1,
                "offset": offset,
                "data": b64_data,
                "checksum": f"0x{checksum:02X}",  # 16进制格式，2位
                "total_size": total_size
            }
            frames.append(frame)
    return frames


if __name__ == "__main__":
    bin_file = r"D:\desktop\My\项目与论文\各种项目\质量项目\工业震动\嵌入式设计大赛\源码\CH32端\version4\V5\obj\VibrationDetect5.bin"
    frames = split_bin_to_frames(bin_file, block_size=256)

    with open("VibrationDetect.json", "w") as f:
        for frame in frames:
            f.write(json.dumps(frame) + "\n")

    print(f"生成完成！共 {len(frames)} 帧，总大小 {os.path.getsize(bin_file)} 字节")